/*
聊天室投注界面管理中心
*/
cc.Class({
    extends: cc.Component,

    properties: {
        //房间根目录
        chatRoomContent:{
            default:null,
            type:cc.Node
        },
        
        //投注滚动层根目录
        betPageView:{
            default:null,
            type:cc.Node
        },

        //投注界面
        betPanelContent:{
            default:null,
            type:cc.Node
        },

        //投注滚动层界面    
        content:{
            default:null,
            type:cc.Node
        },
   
        //k3面板列表
        fbK3PanelList: { 
            default: [],
            type: cc.Prefab
        },
        //115面板列表
        fb115PanelList: { 
            default: [],
            type: cc.Prefab
        },

        //115面板列表(带乐选)
        fb115PanelList1: { 
            default: [],
            type: cc.Prefab
        },

        //双色球
        fbDuotoneBall:{
            default: [],
            type: cc.Prefab
        },

          //大乐透
        fbBigBall:{
            default: [],
            type: cc.Prefab
        },

        //重庆时时彩
        fbCQSSCList:{
            default: [],
            type: cc.Prefab
        },

        //支付	
        quickRechargePagePrefab:{
            default:null,
            type:cc.Prefab
        },

        //错误日志
        labLog:{
            default:null,
            type:cc.Label
        },

        pvBetView:{
            default:null,
            type:cc.PageView
        },

        _lotteryList:[],
        _panelArray:[],
        _contentArray:[],

        _lotteryId:"",
        _roomID:"",
        _isAutoSel:false,//是否机选
        _canvas:null,
        _duration: 0.3//投注列表效果时间
    },

    // use this for initialization
    onLoad: function () {
        this.initEvent();
        this._isAutoSel = false;
        this._canvas = cc.find("Canvas");
        this.initAddAward();//获取加奖信息
    },

   //初始化事件
    initEvent: function(){
        window.Notification.on("BET_ONCLOSE",function(data){
            this.onCloseBet();
        },this);
        window.Notification.on("BET_ONPAY",function(data){
            this.payBtnCallback(data);
        },this);
        
        window.Notification.on("BET_NEXTPAGE",function(data){
            this.onNextPage(data);
        },this);
    },

    //初始化信息
    init: function(lotteryId)
    {
        this._lotteryId = lotteryId;
        if(this._lotteryList.length > 0)
            return;
        //添加投注界面
        this._lotteryList.push(this.fbBigBall);
        this._lotteryList.push(this.fbDuotoneBall);
        this._lotteryList.push(this.fbK3PanelList);
        this._lotteryList.push(this.fbK3PanelList);
        this._lotteryList.push(this.fb115PanelList);
        this._lotteryList.push(this.fb115PanelList1);
        this._lotteryList.push(this.fbCQSSCList);
        this.initBetCollection();
    },

    //初始化投注面板
    initBetCollection: function(){
        var index = LotteryUtils.getPageByLotteryid(this._lotteryId.toString());
      
        if(this._lotteryList[index] !== null){
            var len = this._lotteryList[index].length;
            this.addBetPanel(index);
        }
    },

    //add投注面板
    addBetPanel:function(index){  
        for(var i = 0;i < this._lotteryList[index].length;i++)
        {
            var betPanel = null; 
            betPanel = cc.instantiate(this._lotteryList[index][i]);
            
            if(betPanel != null){
                betPanel.panelIndex = i;
                this._contentArray.push(betPanel);
                this._panelArray.push(betPanel);
            }

            if(betPanel != null){
                var name = betPanel.name;  
                betPanel.getComponent(name).init(this._lotteryId); 
            }
            this.content.addChild(betPanel);
        }
    },

    //关闭投注面板
    onCloseBet:function(){
        for(var i = 0;i < this._contentArray.length;i++)
        {
            this._contentArray[i].getComponent(this._contentArray[i].name).clearAllBetRecord();
        }

        this.hideBet(this.betPanelContent);
        
        if(cc.sys.isNative){
            cc.inputManager.setAccelerometerEnabled(false);
            cc.systemEvent.off(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);//取消重力检测
         }
    },

    initAddAward:function(){
        var recv = function recv(ret) { 
            if(ret.Code == 0 )
            {
                for(var i=0;i<this._contentArray.length;i++)
                {
                    this._contentArray[i].getComponent(this._contentArray[i].name).showAddAward(ret.Data); 
                }
            }
            else if(ret.Code != 49)
            {
                ComponentsUtils.showTips(ret.Msg);
            }

         }.bind(this);

        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryId,
        };
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDAWARD, data, recv.bind(this),"POST");    
    },

    showBet:function(betNode){
        betNode.opacity = 0;
        betNode.active = true;
        betNode.runAction(cc.sequence(cc.fadeTo(this._duration, 255),cc.callFunc(function(){

        }.bind(this),this))); 
    },

    hideBet:function(betNode){
        betNode.runAction(cc.sequence(cc.fadeTo(this._duration, 0),cc.callFunc(function(){
            betNode.active = false;
        }.bind(this),this))); 
    },

    betNumsByNew:function(nums){
        if(this._contentArray.length>0)
        {
            this._contentArray[0].getComponent(this._contentArray[0].name).autoSelNums(1,1,false,nums); 
        }
    },

    //打开投注面板初始值
    onOpenInfo:function(roomid){
        this._roomID = roomid;
        if(this._contentArray.length>0)
        {
            this._contentArray[this._contentArray.length-1].getComponent(this._contentArray[this._contentArray.length-1].name).initReset(); 
        }

        this.betPageView.getComponent("PageViewex").setCurrentPageIndex(0);
        this.betPageView.getComponent("PageViewex").scrollToLeft(0.1);

        this.showBet(this.betPanelContent);
       
         // open Accelerometer 打开重力
        this.SHAKE_THRESHOLD = 150;//150 加速度变化临界值
        this.UPTATE_INTERVAL_TIME = 100;// 两次检测的时间间隔
        this.last_update = 0;
        this.accx = 0 ;
        this.accy = 0 ;
        this.accz = 0 ;
        this.last_x = 0 ;
        this.last_y = 0 ;
        this.last_z = 0 ;
        if (cc.sys.isNative){
            cc.inputManager.setAccelerometerEnabled(true);
            cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);
        }
    },

    onDeviceMotionEvent :function(event) {
        this.accx = event.acc.x;
        this.accy =  event.acc.y;
        this.accz = event.acc.z; 
    },

    update:function(dt){
        var canvasChildren = this._canvas.children;
        if(canvasChildren[canvasChildren.length-1].name == "lottery_quickRecharge"
        || (canvasChildren[canvasChildren.length-1].name == "BetCartPage" 
        && canvasChildren[canvasChildren.length-1].active == true))
        {
            return; 
        }
        var curTime = new Date().getTime();
        var diffTime  = curTime-this.last_update;
        // 每隔100ms进行判断
        if (diffTime>this.UPTATE_INTERVAL_TIME) {
            var speed = Math.abs(this.accx +this.accy + this.accz - this.last_x - this.last_y - this.last_z) / diffTime * 10000;
            // 判断手机确实发生了摇动而不是正常的移动
            this.last_update = curTime;
            if (speed >= this.SHAKE_THRESHOLD) {
                if(!this._isAutoSel)
                {
                    this._isAutoSel = true;
                    var dex = this.betPageView.getComponent("PageViewex").getCurrentPageIndex();
                    if(this._contentArray.length>=dex+1)
                    {
                        this._contentArray[dex].getComponent(this._contentArray[dex].name).randomSelectCallBack();
                    }

                    this.node.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(function(){//延迟1s进行加载
                        this._isAutoSel = false;
                    }.bind(this))));     
                }
            }   
            this.last_x = this.accx;
            this.last_y = this.accy;
            this.last_z = this.accz;
        }
    },

    ontest:function(){
        var dex = this.betPageView.getCurrentPageIndex();
        if(this._contentArray.length>=dex+1)
        {
            this._contentArray[dex].getComponent(this._contentArray[dex].name).randomSelectCallBack();
        }
    },

     //翻页
    onNextPage:function(index){
        var dex = this.betPageView.getComponent("PageViewex").getCurrentPageIndex();
        var maxdex = this.betPageView.getComponent("PageViewex").getCurrentPageIndex();
        
        var nextIdx = dex+index;
      
        if(nextIdx<0)
        {
            nextIdx = 0;
        }
        this.betPageView.getComponent("PageViewex").scrollToPage(nextIdx,0.1);
    },

    //付款
    payBtnCallback:function(data){
         var dataRev = data;
         var recv = function(ret){     
            ComponentsUtils.unblock();
            var obj = ret.Data;
            if(ret.Code == 49)
            {
                this.payBtnCallback(dataRev);
                return;
            }
            if(ret.Code === 0 || ret.Code === 90){//预售中可以购买
                var isuseNum = obj.IsuseNum;      
                var endTimeDate = Utils.getDateForStringDate(obj.EndTime.toString());  
                var endTimeStamp = Date.parse(endTimeDate)/1000;
             
                var recv0 = function(ret0){
                    ComponentsUtils.unblock();
                    var timestamp = Date.parse(new Date())/1000;
                    var leftTimeStamp = endTimeStamp - parseInt(ret0.ServerTime/1000);
                    if(leftTimeStamp <= 0){
                        //cc.log("当前期数已截止");
                        ComponentsUtils.showTips("当前期数已截止");
                        return;
                    }
                    else
                    {
                        var moneyTemp =LotteryUtils.moneytoClient(dataRev.money);
                        var data = {
                             lotteryID:this._lotteryId,    
                             lotteryMoney:moneyTemp,
                             isuseid:obj.IsuseNum,
                             endTime:obj.EndTime,
                             beginTime:obj.BeginTime,
                             baseData:dataRev.dataBase,
                             otherData:dataRev.otherBase,
                             buyType:dataRev.buyType
                        }
                        var quickPayCallback = function(ret){
                            data.lotteryMoney = ret.payMoney;
                            this.doBalancePay(data,ret);
                        }.bind(this);
                        var quickRechargePage = cc.instantiate(this.quickRechargePagePrefab);
                        quickRechargePage.getComponent("lottery_quickRecharge").init(this._lotteryId, obj.IsuseNum, dataRev.money, dataRev.buyType,true,quickPayCallback);                        
                        this._canvas.addChild(quickRechargePage);
                    }
                }.bind(this);    
                var data = {
                    Token:User.getLoginToken(),
                }
                CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETSERVERTIME, data, recv0.bind(this),"POST");  
                ComponentsUtils.block();
            }else{
                ComponentsUtils.showTips(ret.Msg);
                return;
            }
        }.bind(this);

        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryId,
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETRECURRENTISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block(); 
    },

    //账户余额支付
    doBalancePay:function(dataBase,couponsBase){
        var betData = "";
        var istr = dataBase.baseData.substr(0, 1);
        if(istr != "[")
        {
            betData = "[" +dataBase.baseData + "]";
        }
        else
        {
            betData = dataBase.baseData;
        }
        
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                this.onCloseBet();
                ComponentsUtils.showTips("支付成功");
                window.Notification.emit("moneyShow",null);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);

        var data = {
            Token:User.getLoginToken(),
            IsuseNum:dataBase.isuseid,
            BeginTime:dataBase.beginTime,
            EndTime:dataBase.endTime,
            RoomCode:this._roomID,
            BetData:betData,
            ChaseData:dataBase.otherData,
            UserCode:User.getUserCode(),
            LotteryCode:dataBase.lotteryID,
            BuyType:dataBase.buyType,//0代购 1追号 2跟单
            Amount:dataBase.lotteryMoney,
            Coupons:couponsBase.data,
            PaymentType:couponsBase.paymentType,//1.余额彩豆购彩券支付 2.余额支付 3.购彩券支付 4.彩豆支付 5.余额和购彩券支付 6.余额和彩豆支付 7.彩豆和购彩券支付
            Gold:couponsBase.gold//彩豆支付
        }
        
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.REQUESTBET, data, recv.bind(this),"POST");      
        ComponentsUtils.block(); 
    },
    
    //清理所有面板
    clearAllBetRecord:function(){
        for(var i = 0; i<this._contentArray.length; i++){
            var name = this._contentArray[i].name;
            //把所有面板的选中都分析一遍
            this._contentArray[i].getComponent(name).clearAllBetRecord();
        }
    }

});
    